package com.tanhua.server.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.utils.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.concurrent.TimeUnit;

/**
 * @author feihao
 * @version 1.0
 * @date 2021/6/30 16:25
 */

@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice {

    @Value("${tanhua.cache.enable}")
    private Boolean enableCache;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        // 判断是否支持 1.有cache,开关为开，是get请求：
        return methodParameter.hasMethodAnnotation(Cache.class)
                && methodParameter.hasMethodAnnotation(GetMapping.class)
                && enableCache;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (ObjectUtils.isEmpty(o)) {
            return null;
        }

        String redisValue = null;
        try {
            if (o instanceof String) {   //如果返回值是String类型，强转进行赋值给redisValue
                redisValue = (String) o;
            } else {
                redisValue = OBJECT_MAPPER.writeValueAsString(o);
            }

            String redisKey = RedisCacheInterceptor.createRedisKey(((ServletServerHttpRequest) serverHttpRequest).getServletRequest());

            //设置键值对到redis:
            //从cache获取时间值：
            Cache c = methodParameter.getMethodAnnotation(Cache.class);

            redisTemplate.opsForValue().set(redisKey, redisValue, Long.valueOf(c.time()), TimeUnit.SECONDS);

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return o;
    }
}
